package a01_数组;

/**
 * <p>
 * a11_二分查找
 * </p>
 *
 * @author flyduck
 * @since 2024-06-12
 */
//提示：
//
//你可以假设 nums 中的所有元素是不重复的。
//n 将在 [1, 10000]之间。
//nums 的每个元素都将在 [-9999, 9999]之间。
public class a02_二分查找复习5 {

    public static void main(String[] args) {
        int target = 9;
        int[] nums = {-1,0,3,5,9,12};
        int result = search(nums, target);
        System.out.println("result = " + result);
    }

    public static int search(int[] nums, int target) {
        int leftIdx = 0;
        int rightIdx = nums.length - 1;
        int middleIdx = leftIdx + (rightIdx - leftIdx)/2;
        while (leftIdx <= rightIdx){
            if(target > nums[middleIdx]){
                leftIdx = middleIdx + 1;
                middleIdx = leftIdx + (rightIdx - leftIdx)/2;
            }else if(target < nums[middleIdx]){
                rightIdx = middleIdx - 1;
                middleIdx = leftIdx + (rightIdx - leftIdx)/2;
            }else {
                return middleIdx;
            }
        }
        return -1;
    }
}
